package com.yishu.servlet;

import com.yishu.Dao.UserDao;
import com.yishu.entity.User;
import com.yishu.util.DBConnection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;

public class RegisterServlet extends HttpServlet {

    DBConnection dbConnection = new DBConnection();
    UserDao userDao = new UserDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String userName = req.getParameter("userName");
        String password = req.getParameter("password");

        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);

        try {
            Connection connection = dbConnection.getCon();
            int result = userDao.userRegister(connection,user);
            dbConnection.closeCon(connection);

            if(result == 1) {
                req.setAttribute("result","注册成功,点击登录!");
                req.setAttribute("userName",userName);
                req.setAttribute("password",password);
                req.getRequestDispatcher("/userLogin.jsp").forward(req,resp);
            }else {
                req.setAttribute("result","注册失败");
                resp.sendRedirect("/register.jsp");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
